package cn.zhaoyuening.hnistalumnirecord.service.impl;

import cn.zhaoyuening.hnistalumnirecord.dao.NewsDao;
import cn.zhaoyuening.hnistalumnirecord.domain.News;
import cn.zhaoyuening.hnistalumnirecord.service.NewsService;
import cn.zhaoyuening.hnistalumnirecord.utils.JsonDataGridData;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.*;
import org.apache.lucene.util.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhao on 17-1-17.
 */
@Service
public class NewsServiceImpl extends BaseServiceImpl<News> implements NewsService {

    private IndexWriter indexWriter ;

    private IndexSearcher indexSearcher;

    @Autowired
    public void setIndexWriter(IndexWriter indexWriter) {
        this.indexWriter = indexWriter;
    }

    @Autowired
    public void setIndexSearcher(IndexSearcher indexSearcher) {
        this.indexSearcher = indexSearcher;
    }

    @Override
    public List<News> findByModuleId(Serializable moduleId,int pageNumber, int pageSize) {
        List<News> list ;
        if (pageSize < 0) {
            //获取该module所有news
            list = getDao().findAll("moduleId = ? ORDER by orderCount desc,date", new Object[]{moduleId});
        }else {
            int startIndex = (pageNumber-1)*(pageSize+1)-1;
            list = getDao().findAll("moduleId = ? ORDER by orderCount desc,date", new Object[]{moduleId},startIndex, pageSize);
        }
        return list;
    }

    @Override
    public long getTotalRecordByModuleId(Serializable id) {
        return ((NewsDao)getDao()).getTotalRecordByModuleId(id);
    }

    @Override
    public JsonDataGridData findByAdvancedQuery(Integer selectModule, String selectTitle, int startIndex, int pageSize) {
        StringBuilder builder = new StringBuilder();
        List<Object> list = new ArrayList();
        String condition = null;
        Object[] params = null;
        if (selectModule!=null&&selectModule>=0){
            builder.append("and moduleId = ? ");
            list.add(selectModule);

        }

        if (selectTitle!=null&&(!selectTitle.equals(""))){
            builder.append("and title LIKE ?");
            list.add("%"+selectTitle+"%");
        }
        List<News> newsList;
        long total;
        if (list.size() == 0) {
            newsList = this.findAll(null, null, startIndex, pageSize);
            total = getDao().getTotalRecord();
        }else {
            newsList = this.findAll(builder.toString(), list.toArray(), startIndex, pageSize);
            total = ((NewsDao) getDao()).getTotalRecordByModuleIdAndTitle(selectModule, selectTitle);
        }
        JsonDataGridData jdgd = new JsonDataGridData();
        jdgd.setRows(newsList);
        jdgd.setTotal(total);
        return jdgd;
    }

    @Override
    public void updateOrderCountById(Integer id, Integer orderCount) {
        News news = getDao().findById(id);
        news.setOrderCount(orderCount);
    }


    public void save(News news) {
        super.save(news);
        //添加索引
        Document document = new Document();
        Field idField = new IntField("id", news.getId(), Field.Store.YES);
        Field titleField = new TextField("title", news.getTitle(), Field.Store.YES);
        Field contentField = new TextField("content", news.getContent(), Field.Store.NO);
        Field intrduceField = new TextField("intrduce", news.getIntrduce(), Field.Store.YES);
        Field authorField = new StringField("author", news.getAuthor(), Field.Store.YES);
        Field thumbnailPathField = new StringField("thumbnailPath", news.getThumbnailPath(), Field.Store.YES);
        document.add(idField);
        document.add(titleField);
        document.add(contentField);
        document.add(authorField);
        document.add(thumbnailPathField);

        try {
            indexWriter.addDocument(document);
        } catch (IOException e) {

        }
    }

    @Override
    public void delete(News news) {
        super.delete(news);

        //删除索引
        Query query = new TermQuery(new Term("id", news.getId().toString()));
        try {
            indexWriter.deleteDocuments(query);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<News> search(String searchContent) {
        String[] queryList = new String[]{searchContent, searchContent, searchContent, searchContent};
        String[] fields ={ "title", "intrduce", "content","author" };
        BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD,
                BooleanClause.Occur.SHOULD,
                BooleanClause.Occur.SHOULD,
                BooleanClause.Occur.SHOULD};

        List<News> newsList = new ArrayList<>();
        try {
            Query q = MultiFieldQueryParser.parse(Version.LUCENE_44,queryList,fields,new IKAnalyzer());
            TopDocs topDocs = this.indexSearcher.search(q, 20);
            for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
                Document doc = indexSearcher.doc(scoreDoc.doc);
                int id = Integer.parseInt(doc.get("id"));
                News news = getDao().findById(id);

                newsList.add(news);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return newsList;
    }
}
